package com.mayikt;

import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * @Author: maplefire
 * @Description: SemaphoreTest
 * @Date: 2022/09/02 17:32
 */
class ThreadDemo extends Thread {
    private String name;
    private Semaphore semaphore;

    public ThreadDemo(String name, Semaphore semaphore) {
        this.name = name;
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "开始上厕所..");
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "结束上厕所..");
        semaphore.release();
    }
}

public class SemaphoreTest {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            new ThreadDemo("第" + (i + 1) + "个人", semaphore).start();
        }
    }
}

